package com.hnit.controllers;

import com.hnit.web.DTO.AddressDTO;
import com.hnit.service.AddressService;
import com.hnit.web.Utils.ResponseResult;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    /**
     * 查询用户的所有地址
     * GET /address/user/{userId}
     * @param userId 用户ID
     * @return 包含地址DTO列表的统一响应
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<ResponseResult> getAddressesByUserId(@PathVariable Long userId) {
        List<AddressDTO> addresses = addressService.getAddressesByUserId(userId);
        return ResponseEntity.ok(ResponseResult.ok("查询成功").setData(addresses));
    }

    /**
     * 添加用户地址
     * POST /address
     * @param addressDTO 地址信息
     * @return 包含添加成功后地址DTO的统一响应
     */
    @PostMapping
    public ResponseEntity<ResponseResult> addAddress(@Validated @RequestBody AddressDTO addressDTO) {
        try {
            AddressDTO addedAddress = addressService.addAddress(addressDTO);
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(ResponseResult.ok("地址添加成功").setData(addedAddress));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("地址添加失败: " + e.getMessage()));
        }
    }

    /**
     * 更新用户地址
     * PUT /address/{addressId}
     * @param addressId 地址ID
     * @param addressDTO 地址信息
     * @return 包含更新成功后地址DTO的统一响应
     */
    @PutMapping("/{addressId}")
    public ResponseEntity<ResponseResult> updateAddress(@PathVariable Long addressId, @Validated @RequestBody AddressDTO addressDTO) {
        if (!addressId.equals(addressDTO.getAddressId())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ResponseResult.error("请求路径中的地址ID与请求体中的地址ID不一致"));
        }
        try {
            AddressDTO updatedAddress = addressService.updateAddress(addressDTO);
            return ResponseEntity.ok(ResponseResult.ok("地址更新成功").setData(updatedAddress));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ResponseResult.error("请求参数错误: " + e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("地址更新失败: " + e.getMessage()));
        }
    }

    /**
     * 删除用户地址
     * DELETE /address/{addressId}
     * @param addressId 地址ID
     * @return 操作结果的统一响应
     */
    @DeleteMapping("/{addressId}")
    public ResponseEntity<ResponseResult> deleteAddress(@PathVariable Long addressId) {
        try {
            boolean success = addressService.deleteAddress(addressId);
            if (success) {
                return ResponseEntity.ok(ResponseResult.ok("地址删除成功"));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(ResponseResult.error("地址删除失败，地址ID不存在: " + addressId));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("地址删除失败: " + e.getMessage()));
        }
    }

    /**
     * 获取地址详情
     * GET /address/{addressId}
     * @param addressId 地址ID
     * @return 包含地址DTO的统一响应
     */
    @GetMapping("/{addressId}")
    public ResponseEntity<ResponseResult> getAddressById(@PathVariable Long addressId) {
        AddressDTO addressDTO = addressService.getAddressById(addressId);
        if (addressDTO != null) {
            return ResponseEntity.ok(ResponseResult.ok("查询成功").setData(addressDTO));
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ResponseResult.error("地址不存在，ID: " + addressId));
        }
    }

    /**
     * 设置默认地址
     * PUT /address/setDefault/{addressId}/{userId}
     * @param addressId 地址ID
     * @param userId 用户ID
     * @return 操作结果的统一响应
     */
    @PutMapping("/setDefault/{addressId}/{userId}")
    public ResponseEntity<ResponseResult> setDefaultAddress(@PathVariable Long addressId, @PathVariable Long userId) {
        boolean success = addressService.setDefaultAddress(addressId, userId);
        if (success) {
            return ResponseEntity.ok(ResponseResult.ok("默认地址设置成功"));
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ResponseResult.error("默认地址设置失败，地址ID不存在或不属于该用户: " + addressId));
        }
    }
}